package com.xinyi.basic.popup

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow

/**
 * @author 新一
 * @date 2023/7/20 9:38
 * @description PopupWindow基类
 *
 * 该类不够健硕，只适合做小浮窗，建议采用如下popupWindow库：
 *  Android下打造通用便捷的PopupWindow弹窗库：https://github.com/razerdp/BasePopup
 *  implementation 'io.github.razerdp:BasePopup:3.2.1'
 */
abstract class BasePopupWindow(private val mContext: Context) {

    private lateinit var _popupWindow: PopupWindow
    private lateinit var  _convertView: View

    val popupWindow: PopupWindow get() = _popupWindow
    val convertView: View get() = _convertView

    init {
        this.initPopupWindow()
        this.initViews()
        this.initParams()
        this.initListeners()
    }

    protected open fun initPopupWindow() {
        _convertView = View.inflate(mContext, initLayoutId(), null)
    }

    protected abstract fun initLayoutId(): Int

    protected open fun initViews() { }

    protected open fun initParams() {
        _popupWindow = PopupWindow(_convertView, LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        _popupWindow.isFocusable = true // 使其聚集
        _popupWindow.isTouchable = true // 允许触摸

        setDismissOnTouchOutside()
    }

    protected open fun initListeners() { }

    protected open fun isShowing(): Boolean {
        return _popupWindow.isShowing
    }

    /**
     * 设置是否允许在外点击消失 （默认允许）
     */
    protected open fun setDismissOnTouchOutside(dismissOnTouchOutside: Boolean = true) {
        _popupWindow.isOutsideTouchable = dismissOnTouchOutside // 设置允许在外点击消失
        // 解决Android5.1.1 isOutsideTouchable = true 不生效问题
        _popupWindow.setBackgroundDrawable(ColorDrawable(0x00000000))
    }

    protected open fun dismiss() {
        _popupWindow.dismiss()
    }
}